/**
 *   Copyright (c) fanguangping. All rights reserved.
 *   The use and distribution terms for this software are covered by the
 *   Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 *   which can be found in the file epl-v10.html at the root of this distribution.
 *   By using this software in any fashion, you are agreeing to be bound by
 * 	 the terms of this license.
 *   You must not remove this notice, or any other, from this software.
 **/
package org.jfunny.core.mapping;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.jfunny.core.ds.Loop;
import org.jfunny.core.ds.Statement;
import org.jfunny.core.parser.ParserFunny;
import org.jfunny.core.util.StringUtil;

/**
 * 正则模板映射
 * 
 * @author fanguangping
 * 
 */
public class RegexMapping extends AbstractMapping {

	public RegexMapping(String keyName, String key, String value) {
		super(keyName, key, value);
	}

	@Override
	protected List<Statement> getTemplate(String statement) {
		return getRegex("{" + statement + "}");
	}

	private static List<Statement> getRegex(String template) {
		List<Statement> list = new LinkedList<Statement>();

		String before;
		String between;
		String after = template;
		while (after.contains(Loop.PAREN_L)) {
			before = StringUtil.substringBefore(after, Loop.PAREN_L).trim() + "}";
			if (!"{}".equals(before)) {
				//list.add(ParserJfunny.parse(before));
				list.addAll(ParserFunny.parse(before).getChildren());
			}
			between = StringUtil.substringBetween(after, Loop.PAREN_L, Loop.PAREN_R).trim();
			after = StringUtil.substringAfter(after, Loop.PAREN_R).trim();

			if (after.startsWith("?")) {
				after = "{" + StringUtil.substringAfter(after, "?");
				Loop pattern = new Loop(Loop.ZERO_ONE);
				between = "{" + between + "}";
				pattern.setChildren((ArrayList<Statement>) ParserFunny.parse(between).getChildren());
				list.add(pattern);
			}
			else if (after.startsWith("*")) {
				after = "{" + StringUtil.substringAfter(after, "*");
				Loop pattern = new Loop(Loop.ZERO_MORE);
				between = "{" + between + "}";
				pattern.setChildren((ArrayList<Statement>) ParserFunny.parse(between).getChildren());
				list.add(pattern);
			}
			else if (after.startsWith("+")) {
				after = "{" + StringUtil.substringAfter(after, "+");
				Loop pattern = new Loop(Loop.ONE_MORE);
				between = "{" + between + "}";
				pattern.setChildren((ArrayList<Statement>) ParserFunny.parse(between).getChildren());
				list.add(pattern);
			}
			else {
				System.out.println("Error!");
			}

		}
		if (!"{}".equals(after)) {
			//list.add(ParserJfunny.parse(after));
			list.addAll(ParserFunny.parse(after).getChildren());
		}

		return list;
	}

}
